<template>
  <div class="inventory-statistics-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon><DataAnalysis /></el-icon>
          盘点统计
        </h2>
        <p class="page-description">盘点统计分析，包括准确率、效率分析、历史对比等</p>
      </div>
      <div class="header-actions">
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出报告
        </el-button>
        <el-button type="primary" @click="handleGenerateReport">
          <el-icon><Document /></el-icon>
          生成报告
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card shadow="never">
        <el-form :model="filterForm" inline>
          <el-form-item label="统计周期">
            <el-select v-model="filterForm.period" placeholder="选择统计周期" style="width: 150px">
              <el-option label="本月" value="month" />
              <el-option label="本季度" value="quarter" />
              <el-option label="本年" value="year" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围" v-if="filterForm.period === 'custom'">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="filterForm.warehouseId" placeholder="选择仓库" style="width: 150px" clearable>
              <el-option label="全部仓库" value="" />
              <el-option
                v-for="warehouse in warehouseOptions"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="filterForm.categoryId" placeholder="选择分类" style="width: 150px" clearable>
              <el-option label="全部分类" value="" />
              <el-option
                v-for="category in categoryOptions"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 核心指标 -->
    <div class="metrics-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-content">
              <div class="metric-icon accuracy">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ metricsData.accuracy }}%</div>
                <div class="metric-label">平均准确率</div>
                <div class="metric-trend" :class="getTrendClass(metricsData.accuracyTrend)">
                  <el-icon><TrendCharts /></el-icon>
                  {{ metricsData.accuracyTrend > 0 ? '+' : '' }}{{ metricsData.accuracyTrend }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-content">
              <div class="metric-icon efficiency">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ metricsData.efficiency }}</div>
                <div class="metric-label">平均效率(件/小时)</div>
                <div class="metric-trend" :class="getTrendClass(metricsData.efficiencyTrend)">
                  <el-icon><TrendCharts /></el-icon>
                  {{ metricsData.efficiencyTrend > 0 ? '+' : '' }}{{ metricsData.efficiencyTrend }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-content">
              <div class="metric-icon coverage">
                <el-icon><PieChart /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ metricsData.coverage }}%</div>
                <div class="metric-label">盘点覆盖率</div>
                <div class="metric-trend" :class="getTrendClass(metricsData.coverageTrend)">
                  <el-icon><TrendCharts /></el-icon>
                  {{ metricsData.coverageTrend > 0 ? '+' : '' }}{{ metricsData.coverageTrend }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-content">
              <div class="metric-icon cost">
                <el-icon><Money /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">¥{{ metricsData.cost }}</div>
                <div class="metric-label">盘点成本</div>
                <div class="metric-trend" :class="getTrendClass(-metricsData.costTrend)">
                  <el-icon><TrendCharts /></el-icon>
                  {{ metricsData.costTrend > 0 ? '+' : '' }}{{ metricsData.costTrend }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表分析 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 准确率趋势 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <div class="card-header">
                <span>准确率趋势</span>
                <el-button-group size="small">
                  <el-button :type="accuracyChartType === 'line' ? 'primary' : ''" @click="accuracyChartType = 'line'">线图</el-button>
                  <el-button :type="accuracyChartType === 'bar' ? 'primary' : ''" @click="accuracyChartType = 'bar'">柱图</el-button>
                </el-button-group>
              </div>
            </template>
            <div ref="accuracyChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 效率分析 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <div class="card-header">
                <span>效率分析</span>
                <el-button text @click="handleChartRefresh">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div ref="efficiencyChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 分类准确率 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <div class="card-header">
                <span>分类准确率对比</span>
                <el-button text @click="handleChartRefresh">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div ref="categoryChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 人员效率排名 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <div class="card-header">
                <span>人员效率排名</span>
                <el-button text @click="handleChartRefresh">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div ref="staffChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细统计表格 -->
    <div class="table-section">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>详细统计数据</span>
            <div class="header-actions">
              <el-input
                v-model="tableSearchKeyword"
                placeholder="搜索计划名称"
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button @click="handleTableExport">
                <el-icon><Download /></el-icon>
                导出数据
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="filteredTableData"
          stripe
          border
          style="width: 100%"
          :default-sort="{ prop: 'completedDate', order: 'descending' }"
        >
          <el-table-column prop="planName" label="盘点计划" width="180" show-overflow-tooltip />
          <el-table-column prop="warehouseName" label="仓库" width="120" />
          <el-table-column prop="category" label="商品分类" width="120" />
          <el-table-column prop="totalItems" label="盘点商品数" width="120" align="right" />
          <el-table-column prop="completedItems" label="已盘商品数" width="120" align="right" />
          <el-table-column label="完成率" width="100" align="right">
            <template #default="{ row }">
              <el-progress
                :percentage="Math.round((row.completedItems / row.totalItems) * 100)"
                :stroke-width="8"
                :show-text="false"
                style="width: 60px"
              />
              <span style="margin-left: 8px">{{ Math.round((row.completedItems / row.totalItems) * 100) }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="accuracy" label="准确率" width="100" align="right">
            <template #default="{ row }">
              <span :class="getAccuracyClass(row.accuracy)">{{ row.accuracy }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="efficiency" label="效率(件/小时)" width="120" align="right" />
          <el-table-column prop="discrepancyCount" label="差异商品数" width="120" align="right">
            <template #default="{ row }">
              <el-tag v-if="row.discrepancyCount > 0" type="warning" size="small">{{ row.discrepancyCount }}</el-tag>
              <span v-else>0</span>
            </template>
          </el-table-column>
          <el-table-column prop="discrepancyAmount" label="差异金额" width="120" align="right">
            <template #default="{ row }">
              <span :class="getAmountClass(row.discrepancyAmount)">
                {{ row.discrepancyAmount > 0 ? '+' : '' }}¥{{ Math.abs(row.discrepancyAmount).toFixed(2) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="耗时(小时)" width="100" align="right" />
          <el-table-column prop="staffCount" label="参与人数" width="100" align="right" />
          <el-table-column prop="completedDate" label="完成时间" width="110" sortable />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleViewDetail(row)">
                详情
              </el-button>
              <el-button size="small" type="primary" @click="handleViewReport(row)">
                报告
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 对比分析 -->
    <div class="comparison-section">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>历史对比分析</span>
            <el-button-group size="small">
              <el-button :type="comparisonType === 'month' ? 'primary' : ''" @click="comparisonType = 'month'">月度对比</el-button>
              <el-button :type="comparisonType === 'quarter' ? 'primary' : ''" @click="comparisonType = 'quarter'">季度对比</el-button>
              <el-button :type="comparisonType === 'year' ? 'primary' : ''" @click="comparisonType = 'year'">年度对比</el-button>
            </el-button-group>
          </div>
        </template>
        <div ref="comparisonChartRef" class="chart-container-large"></div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="盘点统计详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="detail-content" v-if="currentDetailItem">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="盘点计划">{{ currentDetailItem.planName }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ currentDetailItem.warehouseName }}</el-descriptions-item>
          <el-descriptions-item label="商品分类">{{ currentDetailItem.category }}</el-descriptions-item>
          <el-descriptions-item label="盘点商品数">{{ currentDetailItem.totalItems }}</el-descriptions-item>
          <el-descriptions-item label="已盘商品数">{{ currentDetailItem.completedItems }}</el-descriptions-item>
          <el-descriptions-item label="完成率">{{ Math.round((currentDetailItem.completedItems / currentDetailItem.totalItems) * 100) }}%</el-descriptions-item>
          <el-descriptions-item label="准确率">{{ currentDetailItem.accuracy }}%</el-descriptions-item>
          <el-descriptions-item label="效率">{{ currentDetailItem.efficiency }} 件/小时</el-descriptions-item>
          <el-descriptions-item label="差异商品数">{{ currentDetailItem.discrepancyCount }}</el-descriptions-item>
          <el-descriptions-item label="差异金额">¥{{ Math.abs(currentDetailItem.discrepancyAmount).toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="耗时">{{ currentDetailItem.duration }} 小时</el-descriptions-item>
          <el-descriptions-item label="参与人数">{{ currentDetailItem.staffCount }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-charts" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="12">
              <h4>商品分布</h4>
              <div ref="detailPieChartRef" style="height: 200px"></div>
            </el-col>
            <el-col :span="12">
              <h4>人员效率</h4>
              <div ref="detailBarChartRef" style="height: 200px"></div>
            </el-col>
          </el-row>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleExportDetail">
            导出详情
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  DataAnalysis,
  Download,
  Document,
  Refresh,
  Search,
  RefreshLeft,
  CircleCheck,
  Timer,
  PieChart,
  Money,
  TrendCharts
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentDetailItem = ref(null)
const tableSearchKeyword = ref('')
const accuracyChartType = ref('line')
const comparisonType = ref('month')

// 图表引用
const accuracyChartRef = ref(null)
const efficiencyChartRef = ref(null)
const categoryChartRef = ref(null)
const staffChartRef = ref(null)
const comparisonChartRef = ref(null)
const detailPieChartRef = ref(null)
const detailBarChartRef = ref(null)

// 图表实例
let accuracyChart = null
let efficiencyChart = null
let categoryChart = null
let staffChart = null
let comparisonChart = null
let detailPieChart = null
let detailBarChart = null

// 筛选表单
const filterForm = reactive({
  period: 'month',
  dateRange: [],
  warehouseId: '',
  categoryId: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 选项数据
const warehouseOptions = ref([])
const categoryOptions = ref([])

// 核心指标数据
const metricsData = ref({
  accuracy: 0,
  accuracyTrend: 0,
  efficiency: 0,
  efficiencyTrend: 0,
  coverage: 0,
  coverageTrend: 0,
  cost: 0,
  costTrend: 0
})

// 统计表格数据
const tableData = ref([])

// 计算属性
const filteredTableData = computed(() => {
  let data = tableData.value
  
  if (tableSearchKeyword.value) {
    const keyword = tableSearchKeyword.value.toLowerCase()
    data = data.filter(item => 
      item.planName.toLowerCase().includes(keyword)
    )
  }
  
  return data
})

// 方法
const getTrendClass = (trend) => {
  if (trend > 0) return 'trend-up'
  if (trend < 0) return 'trend-down'
  return 'trend-stable'
}

const getAccuracyClass = (accuracy) => {
  if (accuracy >= 95) return 'accuracy-excellent'
  if (accuracy >= 85) return 'accuracy-good'
  if (accuracy >= 70) return 'accuracy-normal'
  return 'accuracy-poor'
}

const getAmountClass = (amount) => {
  if (amount > 0) return 'amount-positive'
  if (amount < 0) return 'amount-negative'
  return ''
}

const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 加载选项数据
    warehouseOptions.value = [
      { id: 1, name: '主仓库' },
      { id: 2, name: '分仓库A' },
      { id: 3, name: '分仓库B' }
    ]
    
    categoryOptions.value = [
      { id: 1, name: '电子产品' },
      { id: 2, name: '服装' },
      { id: 3, name: '食品' },
      { id: 4, name: '日用品' }
    ]
    
    // 加载核心指标
    metricsData.value = {
      accuracy: 87.5,
      accuracyTrend: 2.3,
      efficiency: 125,
      efficiencyTrend: 8,
      coverage: 92.8,
      coverageTrend: -1.2,
      cost: 15680,
      costTrend: 5.5
    }
    
    // 加载表格数据
    tableData.value = [
      {
        id: 1,
        planName: '2024年第一季度全盘',
        warehouseName: '主仓库',
        category: '全品类',
        totalItems: 1500,
        completedItems: 1485,
        accuracy: 89.2,
        efficiency: 135,
        discrepancyCount: 25,
        discrepancyAmount: -8500.00,
        duration: 12.5,
        staffCount: 8,
        completedDate: '2024-01-15'
      },
      {
        id: 2,
        planName: '电子产品类抽盘',
        warehouseName: '主仓库',
        category: '电子产品',
        totalItems: 350,
        completedItems: 350,
        accuracy: 92.8,
        efficiency: 145,
        discrepancyCount: 8,
        discrepancyAmount: 12000.00,
        duration: 3.2,
        staffCount: 3,
        completedDate: '2024-01-20'
      },
      {
        id: 3,
        planName: '服装类专项盘点',
        warehouseName: '分仓库A',
        category: '服装',
        totalItems: 800,
        completedItems: 795,
        accuracy: 85.6,
        efficiency: 110,
        discrepancyCount: 35,
        discrepancyAmount: -3200.00,
        duration: 7.8,
        staffCount: 5,
        completedDate: '2024-01-25'
      }
    ]
    
    pagination.total = tableData.value.length
    
    // 初始化图表
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const initCharts = () => {
  // 准确率趋势图
  if (accuracyChartRef.value) {
    accuracyChart = echarts.init(accuracyChartRef.value)
    updateAccuracyChart()
  }
  
  // 效率分析图
  if (efficiencyChartRef.value) {
    efficiencyChart = echarts.init(efficiencyChartRef.value)
    const efficiencyOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['计划效率', '实际效率']
      },
      xAxis: {
        type: 'category',
        data: ['第1周', '第2周', '第3周', '第4周']
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 件/小时'
        }
      },
      series: [
        {
          name: '计划效率',
          type: 'bar',
          data: [120, 125, 130, 135],
          itemStyle: {
            color: '#e6a23c'
          }
        },
        {
          name: '实际效率',
          type: 'bar',
          data: [115, 135, 125, 145],
          itemStyle: {
            color: '#67c23a'
          }
        }
      ]
    }
    efficiencyChart.setOption(efficiencyOption)
  }
  
  // 分类准确率图
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
    const categoryOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: ['电子产品', '服装', '食品', '日用品', '图书']
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          name: '准确率',
          type: 'bar',
          data: [92.8, 85.6, 94.2, 88.9, 91.5],
          itemStyle: {
            color: function(params) {
              const colors = ['#67c23a', '#f56c6c', '#67c23a', '#e6a23c', '#67c23a']
              return colors[params.dataIndex]
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}%'
          }
        }
      ]
    }
    categoryChart.setOption(categoryOption)
  }
  
  // 人员效率排名图
  if (staffChartRef.value) {
    staffChart = echarts.init(staffChartRef.value)
    const staffOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 件/小时'
        }
      },
      yAxis: {
        type: 'category',
        data: ['张三', '李四', '王五', '赵六', '钱七']
      },
      series: [
        {
          name: '效率',
          type: 'bar',
          data: [165, 155, 145, 135, 125],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#409eff' },
              { offset: 1, color: '#66b1ff' }
            ])
          },
          label: {
            show: true,
            position: 'right',
            formatter: '{c}'
          }
        }
      ]
    }
    staffChart.setOption(staffOption)
  }
  
  // 历史对比图
  if (comparisonChartRef.value) {
    comparisonChart = echarts.init(comparisonChartRef.value)
    updateComparisonChart()
  }
}

const updateAccuracyChart = () => {
  if (!accuracyChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['准确率', '目标准确率']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      min: 70,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '准确率',
        type: accuracyChartType.value,
        data: [85.2, 87.8, 89.2, 86.5, 88.9, 87.5],
        itemStyle: {
          color: '#409eff'
        },
        smooth: true
      },
      {
        name: '目标准确率',
        type: 'line',
        data: [90, 90, 90, 90, 90, 90],
        itemStyle: {
          color: '#f56c6c'
        },
        lineStyle: {
          type: 'dashed'
        }
      }
    ]
  }
  accuracyChart.setOption(option)
}

const updateComparisonChart = () => {
  if (!comparisonChart) return
  
  let xAxisData, seriesData
  
  switch (comparisonType.value) {
    case 'month':
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月']
      seriesData = {
        accuracy: [85.2, 87.8, 89.2, 86.5, 88.9, 87.5],
        efficiency: [120, 125, 135, 130, 140, 125],
        cost: [18000, 16500, 15800, 17200, 14900, 15680]
      }
      break
    case 'quarter':
      xAxisData = ['Q1', 'Q2', 'Q3', 'Q4']
      seriesData = {
        accuracy: [87.4, 88.2, 86.8, 87.5],
        efficiency: [127, 132, 128, 125],
        cost: [50300, 48200, 51000, 47160]
      }
      break
    case 'year':
      xAxisData = ['2021', '2022', '2023', '2024']
      seriesData = {
        accuracy: [82.5, 85.8, 87.2, 87.5],
        efficiency: [105, 118, 125, 125],
        cost: [180000, 165000, 195000, 188640]
      }
      break
  }
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['准确率(%)', '效率(件/小时)', '成本(元)']
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: [
      {
        type: 'value',
        name: '准确率(%)/效率',
        position: 'left'
      },
      {
        type: 'value',
        name: '成本(元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '准确率(%)',
        type: 'line',
        data: seriesData.accuracy,
        itemStyle: { color: '#409eff' },
        smooth: true
      },
      {
        name: '效率(件/小时)',
        type: 'line',
        data: seriesData.efficiency,
        itemStyle: { color: '#67c23a' },
        smooth: true
      },
      {
        name: '成本(元)',
        type: 'line',
        yAxisIndex: 1,
        data: seriesData.cost,
        itemStyle: { color: '#e6a23c' },
        smooth: true
      }
    ]
  }
  comparisonChart.setOption(option)
}

const handleFilter = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(filterForm, {
    period: 'month',
    dateRange: [],
    warehouseId: '',
    categoryId: ''
  })
  handleFilter()
}

const handleRefresh = () => {
  loadData()
}

const handleChartRefresh = () => {
  if (accuracyChart) accuracyChart.resize()
  if (efficiencyChart) efficiencyChart.resize()
  if (categoryChart) categoryChart.resize()
  if (staffChart) staffChart.resize()
  if (comparisonChart) comparisonChart.resize()
}

const handleViewDetail = (row) => {
  currentDetailItem.value = row
  detailDialogVisible.value = true
  
  nextTick(() => {
    initDetailCharts()
  })
}

const initDetailCharts = () => {
  // 详情饼图
  if (detailPieChartRef.value) {
    detailPieChart = echarts.init(detailPieChartRef.value)
    const pieOption = {
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: '60%',
          data: [
            { value: 1460, name: '正常商品' },
            { value: 25, name: '差异商品' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    detailPieChart.setOption(pieOption)
  }
  
  // 详情柱图
  if (detailBarChartRef.value) {
    detailBarChart = echarts.init(detailBarChartRef.value)
    const barOption = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['张三', '李四', '王五']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          type: 'bar',
          data: [165, 155, 145],
          itemStyle: {
            color: '#409eff'
          }
        }
      ]
    }
    detailBarChart.setOption(barOption)
  }
}

const handleViewReport = (row) => {
  ElMessage.info('查看报告功能开发中')
}

const handleExport = () => {
  ElMessage.info('导出报告功能开发中')
}

const handleGenerateReport = () => {
  ElMessage.info('生成报告功能开发中')
}

const handleTableExport = () => {
  ElMessage.info('导出数据功能开发中')
}

const handleExportDetail = () => {
  ElMessage.info('导出详情功能开发中')
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 监听图表类型变化
watch(accuracyChartType, () => {
  updateAccuracyChart()
})

watch(comparisonType, () => {
  updateComparisonChart()
})

// 生命周期
onMounted(() => {
  loadData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    handleChartRefresh()
    if (detailPieChart) detailPieChart.resize()
    if (detailBarChart) detailBarChart.resize()
  })
})
</script>

<style scoped>
.inventory-statistics-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left .page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left .page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-section,
.metrics-section,
.charts-section,
.table-section,
.comparison-section {
  margin-bottom: 20px;
}

.metric-card {
  border: none;
  transition: all 0.3s;
}

.metric-card:hover {
  transform: translateY(-2px);
}

.metric-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.metric-icon.accuracy {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.metric-icon.efficiency {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.metric-icon.coverage {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.metric-icon.cost {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.metric-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.trend-stable {
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.chart-container-large {
  width: 100%;
  height: 400px;
}

.accuracy-excellent {
  color: #67c23a;
  font-weight: 600;
}

.accuracy-good {
  color: #409eff;
  font-weight: 600;
}

.accuracy-normal {
  color: #e6a23c;
  font-weight: 600;
}

.accuracy-poor {
  color: #f56c6c;
  font-weight: 600;
}

.amount-positive {
  color: #67c23a;
  font-weight: 600;
}

.amount-negative {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  padding: 20px 0;
}

.detail-charts h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inventory-statistics-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .metrics-section .el-col {
    margin-bottom: 16px;
  }
  
  .charts-section .el-col {
    margin-bottom: 20px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container-large {
    height: 300px;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>